package XMLTest;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.crypto.dsig.Transform;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class test1 {
    public static void main(String[] args) throws ParserConfigurationException, TransformerException {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document doc=builder.newDocument();
        doc.createElement("root");

        Element root=doc.createElement("peoples");

        Element lin1= doc.createElement("people");
        lin1.setAttribute("country","中国");
        lin1.setAttribute("id","1");
        Element name1= doc.createElement("name");
        name1.setTextContent("张飞");
        Element age1= doc.createElement("age");
age1.setTextContent("45");

        lin1.appendChild(name1);
        lin1.appendChild(age1);

        Element lin2= doc.createElement("people");
        lin1.setAttribute("country","中国");
        lin1.setAttribute("id","2");
        Element name2= doc.createElement("name");
        name2.setTextContent("诸葛亮");
        Element age2= doc.createElement("age");
age2.setTextContent("45");
        lin2.appendChild(name1);
        lin2.appendChild(age1);

        root.appendChild(lin1);
        root.appendChild(lin2);

        doc.appendChild(root);

        TransformerFactory factory1=TransformerFactory.newInstance();
        Transformer transformer=factory1.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8");
        transformer.setOutputProperty("encoding","UTF-8");
        transformer.transform(
                new DOMSource(doc),
                new StreamResult(new File("D:/qqqqqqqqqqqqqqqqqq.xml"))
        );


    }
}
